﻿using Sino.CapacityCloud.Services;
using Sino.WebApi.Framework.Abstractions.Cryptography;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Sino.CapacityCloud.WebApi.Utilities
{

    public class TokenGeneratorWrapper
        : ITokenGenerator
    {

        private readonly ITokenGenertationService _tokenGenertationService;

        public bool this[string token]
        {
            get
            {
                return this._tokenGenertationService.ValidateAsync(token).GetAwaiter().GetResult();
            }
        }

        public TimeSpan Expire
        {
            get
            {
                return this._tokenGenertationService.Expire;
            }
            set
            {
                this._tokenGenertationService.Expire = value;
            }
        }

        public TokenGeneratorWrapper(ITokenGenertationService tokenGenertationService)
        {
            this._tokenGenertationService = tokenGenertationService;
        }

        public DateTime ExtractCreationTime(string token)
        {
            return this._tokenGenertationService.ParseCreationTimeAsync(token).GetAwaiter().GetResult();
        }

        public string Generate()
        {
            return this._tokenGenertationService.GenerateAsync().GetAwaiter().GetResult();
        }

        public string Generate(DateTime time)
        {
            return this._tokenGenertationService.GenerateAsync(time).GetAwaiter().GetResult();
        }

        public bool ValidateToken(string token)
        {
            return this._tokenGenertationService.ValidateAsync(token).GetAwaiter().GetResult();
        }

        public bool ValidateToken(string token, out TimeSpan estimate)
        {
            return this.ValidateToken(token, this.Expire, out estimate);
        }

        public bool ValidateToken(string token, TimeSpan expire, out TimeSpan estimate)
        {
            DateTime actualExpire;
            return this.ValidateToken(token, expire, out estimate, out actualExpire);
        }

        public bool ValidateToken(string token, TimeSpan expire, out TimeSpan estimate, out DateTime expireTime)
        {
            var creationTime = this._tokenGenertationService.ParseCreationTimeAsync(token).GetAwaiter().GetResult();
            expireTime = creationTime + expire;
            if (expireTime < DateTime.Now)
            {
                estimate = expireTime - DateTime.Now;
            }
            else
            {
                estimate = TimeSpan.Zero;
            }
            return this._tokenGenertationService.ValidateAsync(token).GetAwaiter().GetResult();
        }

    }

}